import { getData } from '~/server/plugins/getData'
import { replaceImageDomains } from '~/utils/configHelper'

const SEARCH_WEIGHTS = {
  name: 10,
  category: 5,
  developer: 3,
  description: 2,
  tags: 4
}

// 简化模糊搜索逻辑
function fuzzySearch(text: string, key: string): number {
  if (!text || !key) return 0
  const t = text.toLowerCase()
  const k = key.toLowerCase()

  if (t === k) return 100
  if (t.startsWith(k)) return 80
  if (t.includes(k)) return 60

  if (k.length <= 2) return t.includes(k) ? 40 : 0

  // 简易字符序列匹配
  let i = 0, matches = 0
  for (let c of t) if (c === k[i]) { i++; matches++ }
  if (i === k.length) return Math.min(60, 20 + matches*5)

  // 单词边界匹配
  if (t.split(/[\s-_]+/).some(word => word.startsWith(k))) return 50
  return 0
}

function calculateScore(item: any, key: string): number {
  let total = 0, max = 0
  for (const [field, weight] of Object.entries(SEARCH_WEIGHTS)) {
    if (!item[field]) continue
    total += fuzzySearch(String(item[field]), key) * weight
    max += 100 * weight
  }
  return max ? (total / max * 100) : 0
}

export default defineEventHandler(async (event) => {
  try {
    const rawSearchKey = getRouterParam(event, 'searchKey')
    const searchKey = decodeURIComponent(rawSearchKey || '').replace(/\+/g, ' ').trim()
    if (!searchKey) {
      return { success: false, message: '搜索关键词不能为空', data: [], total: 0 }
    }

    // 参数处理
    const { limit = 50, page = 1, sortBy = 'relevance' } = getQuery(event)
    const nLimit = Math.min(Number(limit) || 50, 100)
    const nPage = Number(page) || 1

    const currentData = getData().getCurrentRequestData(event)
    if (!currentData?.data?.allData) {
      return { success: false, message: '无法获取数据', data: [], total: 0 }
    }

    // 搜索与排序
    let results = currentData.data.allData.reduce((acc: any[], item: any) => {
      if (!item?.name) return acc
      const score = calculateScore(item, searchKey)
      if (score > 0) acc.push({ ...item, _score: score })
      return acc
    }, [])

    results.sort((a, b) => {
      if (sortBy === 'name') return a.name.localeCompare(b.name)
      if (sortBy === 'category') return (a.category || '').localeCompare(b.category || '') || a.name.localeCompare(b.name)
      return b._score - a._score
    })

    const uniqueResults = Array.from(
      new Map(results.map(item => [item.desc, item])).values()
    )

    // 分页
    const total = uniqueResults.length
    const totalPages = Math.ceil(total / nLimit)
    const paged = uniqueResults.slice((nPage - 1) * nLimit, nPage * nLimit)
      .map(({ _score, ...item }) => item)
    const hostname = event.node.req.headers.host || ''
    const data = replaceImageDomains(paged, hostname)

    return {
      success: true,
      message: '搜索成功',
      data,
      total,
      page: nPage,
      limit: nLimit,
      totalPages,
      searchKey
    }
  } catch (e: any) {
    console.error('搜索接口错误:', e)
    return {
      success: false,
      message: '搜索过程中发生错误',
      data: [],
      total: 0,
      error: process.env.NODE_ENV === 'development' ? e?.message : undefined
    }
  }
})